package com.ydd.interceptor;

import com.ydd.context.BaseContext;
import com.ydd.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //获取登录数据员工id
        String token = request.getHeader("X-Token");
        if (token == null) {
            response.setStatus(401);
            return false;
        }
        /**
         * 是否过期
         *
         * @param claims
         * @return -1：有效，0：有效，1：过期，2：过期
         */

        Claims claimsBody = JwtUtil.getClaimsBody(token);
        int i = JwtUtil.verifyToken(claimsBody);
        if (i == 0 || i == -1) {
            Long id = Long.valueOf(claimsBody.get("id").toString());
            BaseContext.setCurrentId(id);
            return true;

        } else {
            //否则，发送未认证错误信息
            response.setStatus(401);
            return false;
        }
    }


}
